<?php

namespace Apps\AppApi\Method\User;

use Apps\AppApi\Method\BaseMethod;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\UserBase;
use Apps\Common\Models\QuestionAnswer;
use Apps\Common\Models\Question;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\QuestionFollow;

/**
 * 专家详情（专家回答的问题列表）
 */
class ExpertQuestionList extends BaseMethod
{
    public function run()
    {
    	$user_id = intval($this->getDataItem('user_id', 0));
		$expert_id = intval($this->getDataItem('expert_id', 0));
		$page = intval($this->getDataItem('page', 1));

		if ($expert_id < 1) {
			return $this->errorLog(ResultStatus::URL_PARAM_CANNOT_EMPTY, '缺少必传参数！');
		}

		$limit = $this->getConfig()->limit;
		$offset = ($page - 1) * $limit;

		$list = QuestionAnswer::query()->columns(['question_id'])->where('answer_state = 1 and user_id = ' . $expert_id)->groupBy('question_id')->orderBy('answer_id DESC')->limit($limit, $offset)->execute()->toArray();

		if ($list) {
			$where = '';
			foreach ($list as $val) {
				$where .= $val['question_id'] . ',';
			}
			$where = trim($where, ',');

			$result = Question::query()->columns([
				'question_id',
				'question_tag',
				'question_pics',
				'question_content',
				'question_addtime',
				'u.user_id',
				'u.user_nickname',
				'u.user_cover',
				'u.user_gender'
			])->leftJoin('\Apps\Common\Models\UserBase', 'u.user_id = \Apps\Common\Models\Question.user_id', 'u')->where("question_state = 1 and question_id in({$where})")->execute()->toArray();

			$QuestionFollow = new QuestionFollow();
			foreach ($result as $k => $val) {
				$result[$k]['question_content'] = unserialize(base64_decode($val['question_content'])) ?: $val['question_content'];
				$result[$k]['user_cover'] = PicUrl::UserCover($val['user_cover'], $this->getDi());

				if ($val['question_pics']) {
					$result[$k]['question_pics'] = PicUrl::Question(json_decode($val['question_pics']), $this->getDi());
				}
				if (!is_numeric($val['question_tag'])) {
					$result[$k]['question_tag'] = $val['question_tag'] ? json_decode($val['question_tag'], true) : [];
				} else {
					$result[$k]['question_tag'] = [];
				}

				if ($user_id > 0) {
					$result[$k]['is_collection'] = $QuestionFollow->is_follow($val['question_id'], $user_id);
				} else {
					$result[$k]['is_collection'] = '0';
				}
			}

			$this->setResult($result);
		}
    }
}